package com.taobao.fanli.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.fanli.dao.mapper.UserMapper;
import com.taobao.fanli.dao.model.User;
import com.taobao.fanli.postbean.RedpackInitBean;
import com.taobao.fanli.postbean.RegisterBean;
import com.taobao.fanli.utils.CookieUtil;
import com.taobao.fanli.utils.EncrypDES;
import com.taobao.fanli.vo.Login;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.digester.Digester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * Created by Tao on 2018/4/19.
 */
@Service
public class LoginService {

    private static final Logger logger = LoggerFactory.getLogger("LoginService");

    private static final String ticket = "ticket";

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedPackService redPackService;

    //注册
    public Integer register(RegisterBean registerBean) {
        User userAccount = userMapper.selectByAccount(registerBean.getAccount());
        if(userAccount != null){
            throw new RuntimeException("帐号已注册");
        }
        User user = new User();
        user.setAccount(registerBean.getAccount());
        user.setPassword(DigestUtils.md5Hex(registerBean.getPassword()));
        user.setNickName(registerBean.getNickName());
        user.setRealName(registerBean.getRealName());
        user.setAlipay(registerBean.getAlipay());
        user.setCreateAt(new Date());
        user.setUpdateAt(user.getCreateAt());
        userMapper.insertDynamic(user);
        Integer id = user.getId();
        RedpackInitBean redpackInitBean = new RedpackInitBean();
        redpackInitBean.setUserId(id);
        redpackInitBean.setType(1);
        redPackService.init(redpackInitBean);
        return id;
    }

    //更新密码
    public void updatePassword(Login userByCookie, String password) {
        User user = new User();
        user.setId(userByCookie.getId());
        user.setPassword(DigestUtils.md5Hex(password));
        userMapper.updateDynamic(user);
    }

    public Login login(String account, String password) throws Exception {
        User user = userMapper.selectByAccount(account);
        if (user == null) {
            throw new RuntimeException("没有此用户");
        }
        if(!user.getPassword().equals(DigestUtils.md5Hex(password))){
            throw new RuntimeException("密码错误");
        }
        return getLogin(user);
    }

    private Login getLogin(User user) {
        Login login = new Login();
        login.setAccount(user.getAccount());
        login.setId(user.getId());
        login.setNickName(user.getNickName());
        login.setRealName(user.getRealName());
        login.setAlipay(user.getAlipay());
        login.setFrozenMoney(user.getFrozenMoney());
        login.setReceiveMoney(user.getReceiveMoney());
        login.setTransactionMoney(user.getTransactionMoney());
        return login;
    }

    public Login getUserByCookie(HttpServletRequest request) {
        String id = CookieUtil.getCookieByName(request, ticket);
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        String cookieValue = null;
        try {
            EncrypDES encrypDES = EncrypDES.getEncrypDES();
            byte[] bytes = encrypDES.parseHexStr2Byte(id);
            byte[] encrytor = encrypDES.Decryptor(bytes);
            cookieValue = new String(encrytor);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        User user = userMapper.getOne(Integer.valueOf(cookieValue));
        Login login = getLogin(user);
        return login;
    }

    public void setUserByCookie(Login login, HttpServletResponse response) {
        String id = String.valueOf(login.getId());
        String cookieValue = null;
        try {
            EncrypDES encrypDES = EncrypDES.getEncrypDES();
            byte[] encrytor = encrypDES.Encrytor(id);
            cookieValue = encrypDES.parseByte2HexStr(encrytor);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CookieUtil.setCookie(response, ticket, cookieValue, "");
    }

    public void deleteUserByCookie(HttpServletResponse response){
        CookieUtil.setCookie(response, ticket, null, "", 60);
    }

    public void checkOldPassword(Login userByCookie, String oldPassword) throws RuntimeException {
        User user = userMapper.selectByAccount(userByCookie.getAccount());
        if(!user.getPassword().equals(DigestUtils.md5Hex(oldPassword))){
            throw new RuntimeException("密码错误");
        }
    }
}
